<template>
    <select type="text" ref="input" :value="value">
        <option :value="option.id" v-for="option in options" :key="option.id" v-text="`${option.id}-${option.title}`"></option>
    </select>
</template>

<script>
export default {
    name: 'taginput',
    props: ['value', 'options'],
    data() {
        return {
            selectize: null,
            syncValue: null,
        }
    },
    mounted(){
        this.selectize = $(this.$refs.input).selectize({
            plugins: ['remove_button'],
            maxItems: 10,
            onChange: (value) => {
                if (_.isEqual(value, this.syncValue)) {
                    return
                }
                this.syncValue = _.clone(value)

                const intValue = value ? _.map(value, _.toInteger): []
                this.$emit('input', intValue)
            }
        })[0].selectize
    },
    watch: {
        value(intValue) {
            const v = intValue ? _.map(intValue, _.toString): intValue
            if (_.isEqual(v, this.syncValue)) {
                return
            }
            this.syncValue = _.clone(v)
            this.selectize.setValue(v)
        }
    },
}
</script>

